// pages/confirmOrder/confirmOrder.js

const app = getApp();
let Api = require('../../api/api.js');
Page({
    data: {
        orderList:[],
        tipText:'',
        showToast:false,
        activeTabs:'送自己',
        name:'',
        phone:'',
        area:'',
        addressid:'',
        totalAmount:0, //总价整数部分
        totalAmount_1:'',//总价小数部分
        remark:'',//备注
        showModal:false,
        enterType:'首页进入',
        wsid:'',
        wcids: '', //购物车标识ID，多个逗号隔开
        wcidsArray:[],//
        customvalue: "",//购物车下单的自定义铭牌，数组格式上传（wcid∑value∑wcid∑value） ∑ 符合隔开
        ordernumber:'', // 支付订单号
        orderType: '普通订单',
        showTextarea: true,
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let self = this;
        console.log(options, '--确认订单options--')
        self.setData({
            activeTabs: options.sendType,
            enterType: options.enterType,
        })
        if (options.enterType != '购物车进入') {
            self.setData({
                wsid: options.wsid,
            })
        }
        let listData = [];
        if (options.enterType == '首页进入'){
            listData.push({
                wpViceName: options.wpViceName ,
                customNameplateText: '(输入铭牌内容)', // 自定义铭牌内容
                wpid: options.wpid,
                wpCover: options.wpCover,
                wpName: options.wpName,
                wsOneValue: options.nameplateType,
                wcInt: options.purchaseQuantity,
                wsPrice: parseInt(options.wpPrice),
                wsPrice_1: options.wpPrice.substring(options.wpPrice.length - 2, options.wpPrice.length),
                subtotal: parseInt(options.wpPrice * options.purchaseQuantity),
                subtotal_1: ((options.wpPrice * options.purchaseQuantity).toFixed(2)).substring(((options.wpPrice * options.purchaseQuantity).toFixed(2)).length - 2, ((options.wpPrice * options.purchaseQuantity).toFixed(2)).length),
            })
            self.setData({
                orderList: listData,
                totalAmount: parseInt(options.wpPrice * options.purchaseQuantity),
                totalAmount_1: ((options.wpPrice * options.purchaseQuantity).toFixed(2)).substring(((options.wpPrice * options.purchaseQuantity).toFixed(2)).length - 2, ((options.wpPrice * options.purchaseQuantity).toFixed(2)).length),
            })
            //地址列表展示接口
            Api.get(app.globalData.mallDomain, { 
                doShowAddressList: 1,
                token: app.globalData.token,
            }).then(res => {
                console.log(res, '地址列表展示接口')
                if (res.data.msg == '108') {
                    if (res.data.list != '') {
                        for (let i = 0; i < res.data.list.length; i++) {
                            if (res.data.list[i].isdefault == '1') {
                                self.setData({
                                    name: res.data.list[i].name,
                                    phone: res.data.list[i].phone,
                                    area: res.data.list[i].detaile,
                                    addressid: res.data.list[i].addressid,
                                })
                            }
                        }
                    }
                }
               
            })
        }else{ //详情页面或者购物车进入确认订单页面
            let data = {};
            if (options.enterType == '购物车进入'){ //购物车页面进入的参数
                data = {
                    doShowOrderList: 1,
                    wcids: options.wcids,  //购物车标识ID，多个逗号隔开
                    token: app.globalData.token,
                }
                self.setData({
                    wcids: options.wcids,
                    wcidsArray: options.wcids.split(',')
                })
            }else{ // 详情页面进入的参数
                data = {
                    doShowOrderList: 1,
                    wsids: app.globalData.wpid, //商品属性标识ID   进入详情页面就已经存储了
                    nums: options.purchaseQuantity,
                    token: app.globalData.token,
                }
            }
             //8）展示订单列表（购物车进入/详情页进入）
            Api.get(app.globalData.mallDomain, data).then(res => {
                console.log(res,'--------购物车进入--------')
                if (res.data.list != '') {
                    let totalAmountVal = 0;
                    for (let i = 0; i < res.data.list.length; i++) {
                        listData.push({
                            wpViceName: res.data.list[i].wpViceName,
                            wpid: res.data.list[i].wpId,
                            customNameplateText: '(输入铭牌内容)', // 自定义铭牌内容
                            wpCover: res.data.list[i].wpCover,
                            wpName: unescape(res.data.list[i].wpName),
                            wsOneValue: res.data.list[i].wsOneValue,
                            wcInt: res.data.list[i].wcInt,
                            wsPrice: parseInt(res.data.list[i].wsPrice),
                            wsPrice_1: res.data.list[i].wsPrice.substring(res.data.list[i].wsPrice.length - 2, res.data.list[i].wsPrice.length),
                            subtotal: parseInt(res.data.list[i].wsPrice * res.data.list[i].wcInt),
                            subtotal_1: ((res.data.list[i].wsPrice * res.data.list[i].wcInt).toFixed(2)).substring(((res.data.list[i].wsPrice * res.data.list[i].wcInt).toFixed(2)).length - 2, ((res.data.list[i].wsPrice * res.data.list[i].wcInt).toFixed(2)).length),
                        })
                        totalAmountVal = totalAmountVal + parseFloat(res.data.list[i].wsPrice) * parseFloat(res.data.list[i].wcInt);
                    }
                    //处理两整数相乘
                    let fs = totalAmountVal.toString();
                    let fp = fs.indexOf('.');
                    if (fp < 0) {
                        fp = fs.length;
                        fs += '.';
                    }
                    while (fs.length <= fp + 2) { //小数位小于两位，则补0
                        fs += '0';
                    }
                    if (res.data.DefaultAddress != undefined && res.data.DefaultAddress != null && res.data.DefaultAddress != '') {
                        self.setData({
                            name: res.data.DefaultAddress[0].Name,
                            phone: res.data.DefaultAddress[0].Phone,
                            area: res.data.DefaultAddress[0].Area,
                            orderList: listData,
                            totalAmount: parseInt(totalAmountVal),
                            totalAmount_1: fs.substring(fs.length - 2, fs.length),
                            addressid: res.data.DefaultAddress[0].AddressID,
                        })
                    } else {
                        self.setData({
                            orderList: listData,
                            totalAmount: parseInt(totalAmountVal),
                            totalAmount_1: fs.substring(fs.length - 2, fs.length),
                        })
                    }
                }
            })
        }
    },
    /**
     * 进入输入自定义铭牌页面
     */
    writeNameplate: function (e) {
        let self = this;
        wx.navigateTo({
            url: '../customNameplate/customNameplate?name=' + e.currentTarget.dataset.name + '&src=' + e.currentTarget.dataset.src + '&wpid=' + e.currentTarget.dataset.wpid + '&wcid=' + self.data.wcidsArray[e.currentTarget.dataset.index]
        })
    }, 
    /**
     * 点击提交订单
     */
    toSettlement: function (e) {
        let self = this;
        let data = {};
        if (self.data.enterType == '首页进入') { //13）详情页直接下单参数
            data = {
                doAddOrder: 1,
                wpid: self.data.orderList[0].wpid,
                wsid: self.data.wsid,
                number: self.data.orderList[0].wcInt,
                remark: self.data.remark,
                token: app.globalData.token,
            }
            if (self.data.orderList[0].wsOneValue == '自定义') {
                data["customvalue"] = self.data.orderList[0].customNameplateText
            }
            if (self.data.activeTabs == '送自己') {
                data["addressid"] = self.data.addressid;
                data["giving"] = 1;
            } else if (self.data.activeTabs == '送他人') {
                data["giving"] = 2;
            }
        } else { // 14）购物车下单参数
            data = {
                doAddCarOrder: 1,
                wcid: self.data.wcids,
                remark: self.data.remark,   
                token: app.globalData.token,
            }
            if (self.data.orderList[0].wsOneValue == '自定义') {
                if (self.data.customvalue[0] == '∑'){
                    self.setData({
                        customvalue: self.data.customvalue.substring(1, self.data.customvalue.length)
                    })
                }
                data["customvalue"] = self.data.customvalue
            }
            if (self.data.activeTabs == '送自己') {
                data["addressid"] = self.data.addressid;
                data["giving"] = 1;
            } else if (self.data.activeTabs == '送他人') {
                data["giving"] = 2;
            }
        }
        for (let i = 0; i < self.data.orderList.length; i++) {
            if (self.data.orderList[i].wsOneValue == '自定义' && self.data.orderList[i].customNameplateText == '(输入铭牌内容)') {
                self.setData({
                    tipText: '请输入自定义铭牌内容！',
                    showToast: true,
                })
                setTimeout(function () {
                    self.setData({
                        tipText: '',
                        showToast: false
                    })
                }, 1000)
                return;
            }
        }
        //判断订单中存在不存在自定义订单，存在跳转的转发页面只能转发一次 不存在的话可以多次转发 直到填写地址才不能转发。
        for (let i = 0; i < self.data.orderList.length; i++) {
            if (self.data.orderList[i].wsOneValue == '自定义') {
                self.setData({
                    orderType: '自定义订单'
                })
            }
        }
        
        //  13）详情页直接下单 和    14）购物车下单
        Api.get(app.globalData.mallDomain, data).then(res => {
            console.log(res,'确认订单下单')
            if (res.data.msg == '113' || res.data.msg == '112' ){
                self.setData({
                    showModal: true,
                    showTextarea: false,
                    ordernumber: res.data.ordernumber,
                })
                let pages = getCurrentPages();
                let prevPage = pages[pages.length - 2];  //上一个页面
                prevPage.loadShoppingCartList(); //重新加载购物车列表
            } else {
                self.setData({
                    tipText: '提交信息有误！',
                    showToast: true
                })
                setTimeout(function () {
                    self.setData({
                        tipText: '',
                        showToast: false
                    })
                }, 1000)
            }
        })
    },
    /**
     * 立即支付
     */
    immediatelyPay: function (e) {
        let self = this;
        self.setData({
            showModal: false,
            showTextarea: false,
        })
        //  25、支付请求接口
        Api.get(app.globalData.payUrl, {
            token: app.globalData.token,
            ordernumber: self.data.ordernumber,
        }).then(res => {
            console.log(res)
            wx.requestPayment({
                timeStamp: res.data.timeStamp,
                nonceStr: res.data.nonceStr,
                package: res.data.package,
                signType: res.data.signType,
                paySign: res.data.paySign,
                success: function (res) { 
                    console.log(res)
                    wx.showToast({
                        title: '支付成功',
                        icon: 'success',
                        duration: 1000
                    }) 
                    setTimeout(function(){
                        wx.redirectTo({
                            url: '../paySuccess/paySuccess?sendType=' + self.data.activeTabs + '&orderType=' + self.data.orderType + '&ordernumber=' + self.data.ordernumber
                        })
                    },2000)
                },
            })
        })
    },
    /**
     * 点击取消按钮，关闭弹出框
     */
    closeBg: function (e) {
        let self = this;
        self.setData({
            showModal: false,
            showTextarea: true,
        })
    },
    /**
     * 备注
     */
    bindTextAreaBlur: function (e) {
        let self = this;
        self.setData({
            remark: e.detail.value
        })
    },
    
    /**
     * 点击切换地址
     */
    clickAddress: function(e) {
        let self = this;
        wx.navigateTo({
            url: '../address/address'
        })
    },
    /**
     * 点击tabs
     */
    clickTabs:function(e){
        let self = this;
        if (e.currentTarget.dataset.text == '送他人'){
            self.setData({
                activeTabs:'送他人'
            })
        } else {
            self.setData({
                activeTabs: '送自己'
            })

        }
    },

})